package com.core.thread;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

import org.apache.log4j.Logger;

import com.core.action.TimeAction;
import com.core.interfaces.IScheduledThread;


public class ScheduledThread implements IScheduledThread
{
	
	private static final Logger logger = Logger.getLogger(ScheduledThread.class);
	
	String threadName;
	/** 线程池 **/
	private ScheduledThreadPoolExecutor exe;
	
	private static AtomicInteger id=new AtomicInteger(0);
	/**逻辑线程名称**/
	public static String loopThreadName ="loopThread";
	
	public void init() 
	{
		this.exe = new ScheduledThreadPoolExecutor(1, new Threadfactory());
	}

	
	
	private class Threadfactory implements ThreadFactory {
		@Override
		public Thread newThread(Runnable r) {
			Thread thread = new Thread(r);
			thread.setName(getThreadName());
			return thread;
		}
	}

	public void pushAction(Runnable serverAction) {
		if (exe == null) {
			serverAction.run();
		}
		if(serverAction instanceof TimeAction)
		{
			TimeAction timeAction = (TimeAction)serverAction;
			int size = this.exe.getQueue().size();
			if(size>200)
			{
				logger.warn("消息长度 "+size+"  线程数量 "+this.exe.getPoolSize());
			}
			ScheduledFuture<?> future = this.exe.scheduleWithFixedDelay(timeAction,
					timeAction.getIntervalMill(), timeAction.getIntervalMill(),
					TimeUnit.MILLISECONDS);
			timeAction.setFutrue(future);
			return;
		}
		this.exe.execute(serverAction);
	}


	public void shutDown() {
		if(exe!=null&&!exe.isShutdown())
			this.exe.shutdownNow();
	}

	public String getThreadName() {
		if(this.threadName==null)
		{
			this.threadName = loopThreadName + id.addAndGet(1);
		}
		return this.threadName;
	}
	
	/**执行任务**/
	public void exeTask(Runnable command)
	{
		this.exe.execute(command);
	}

}
